package com.tian.producer;

import com.alibaba.fastjson.JSON;
import com.tian.constant.RabbitMQConstant;
import com.tian.factory.ApplicationContextFactory;
import com.tian.message.IncomeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.UUID;

/**
 * {@code @description:} TODO
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024/1/26 20:59
 * {@code @version:} 1.0
 */
@Slf4j
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Component
public class IncomeProducer {
    @Resource
    private ApplicationContext applicationContext;
    public void send(IncomeMessage incomeMessage) {
        //构建回调返回的数据
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        String content = JSON.toJSONString(incomeMessage);
        this.getScopeRabbitTemplate().convertAndSend(RabbitMQConstant.INCOME_EXCHANGE, RabbitMQConstant.INCOME_ROUTING_KEY, content, correlationData);
        log.info("确认发送ok ," + new Date() + "," + content);
    }


    private RabbitTemplate getScopeRabbitTemplate() {
        RabbitTemplate scopeRabbitTemplate = (RabbitTemplate) applicationContext.getBean("incomeRabbitTemplate");
        log.info("获取新的RabbitTemplate:{}", scopeRabbitTemplate);
        return scopeRabbitTemplate;
    }
}
